﻿using System;
using System.Data;
using System.Xml.Serialization;

namespace Alex.DataLibrary.Tables
{
	[XmlRoot("DataTableCompare")]
    public class DataTableDifference : DataTableStandart
    {
    	public override Enums.TableType TypeTable 
		{ 
			get
			{
                return Enums.TableType.Compare;
			}
		}
    			
    	public DataTableDifference()
    	{
            Table = new DataTable();

            initColumns();
            
            Initialize();
    	}

        public DataTableDifference(string tableName)
        {
            Table = new DataTable(tableName);

            initColumns();

            Initialize();
        }

        private void initColumns()
        {            
            Table.Columns.Add("Parameter");
            Table.Columns.Add("Initial");
            Table.Columns.Add("Model");
            Table.Columns.Add("RelDifference");
            Table.Columns.Add("AbsDifference");

            absRelUnlock(true); 
        }
        
        public override void Initialize()
        {
            Table.RowChanged += DataTableDifference_RowChanged;
        }

        void DataTableDifference_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            DataRow row = e.Row;

            absRelUnlock(false);

            string temp = absDiffCalc(row).ToString();
            
            if (row["AbsDifference"].ToString() != temp)
            {                
                row["AbsDifference"] = temp;                
            }

            temp = relDiffCalc(row).ToString();

            if (row["RelDifference"].ToString() != temp)
            {                
                row["RelDifference"] = temp;                
            }

            absRelUnlock(true);
        }

        private object relDiffCalc(DataRow row)
        {
            try
            {
                return 100*(Convert.ToDouble(row["Model"]) - Convert.ToDouble(row["Initial"])) / Convert.ToDouble(row["Initial"]);
            }
            catch
            {
                return "NaN";
            }
        }

        private object absDiffCalc(DataRow row)
        {
            try
            {
                return Convert.ToDouble(row["Model"]) - Convert.ToDouble(row["Initial"]);
            }
            catch 
            {
                return "NaN";
            }
        }

        private void absRelUnlock(bool locker)
        {
            Table.Columns["RelDifference"].ReadOnly = locker;
            Table.Columns["AbsDifference"].ReadOnly = locker;
        }

        public override string ToString()
        {
            return Table.TableName;
        }
    }
}
